const KEY = 'GOODS'

/**
 * 获取本地商品数据
 */
export const getLocalGoods = () => {
  return wx.getStorageSync(KEY) || {}
}

/**
 * 新增商品到购物车中
 * {goods_id:129,goods_number:1}
 */
export const addGoods = ({ goods_id, goods_number }) => {
  // 1、取出本地存储的商品对象 {goods_id:goods_number}，假设本地{38:1,129:1}
  const localGoods = wx.getStorageSync(KEY) || {}

  // 2、根据传递过来的id，去取出来的本地的商品对象，看传递过来的id是否在本地存在
  // 如果存在，就把之前的商量取出来加上新传入的数量，然后赋值给goods_id，如果不存在则新增一个属性名称:值
  if (localGoods[goods_id]) {
    // 代表之前存在着
    localGoods[goods_id] += goods_number
  } else {
    // 之前没有
    localGoods[goods_id] = goods_number
  }

  // 3、保存回去
  wx.setStorageSync(KEY, localGoods)
}

export const updateGoods = ({ goods_id, goods_number }) => {
  // 1、取出本地存储的商品对象 {goods_id:goods_number}，假设本地{38:1,129:1}
  const localGoods = wx.getStorageSync(KEY) || {}

  // 2、更改商品数量
  localGoods[goods_id] = goods_number

  // 3、保存回去
  wx.setStorageSync(KEY, localGoods)
}

export const deleteGoods = goods_id => {
  // 1、取出本地存储的商品对象 {goods_id:goods_number}，假设本地{38:1,129:1}
  const localGoods = wx.getStorageSync(KEY) || {}

  // 2、删除id对应的商品数据
  delete localGoods[goods_id]

  // 3、保存回去
  wx.setStorageSync(KEY, localGoods)
}

// export {addGoods,updateGoods}
